<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Validate;
use think\Cache;
use app\common\model\Config as ConfigModel;
require_once (ROOT_PATH . 'vendor/smssdk/SmsApi.php');
/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','code','agree'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = input('account');
        $password = input('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 协议内容
     */
    public function agree(){
        $agreement=Config('site.agreement');
        $privacy=Config('site.privacy');
        $prize=Config('site.prize');
        $data['agreement']=$agreement;
        $data['privacy']=$privacy;
        $data['prize']=$prize;//有奖说明
        $this->success('查询成功',$data);
    }
    /**
    * 获取客户端IP
    */
    public function getClientIp() {
        $ip = 'unknown';
        $unknown = 'unknown';
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)) {
            // 使用透明代理、欺骗性代理的情况
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];

        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)) {
            // 没有代理、使用普通匿名代理和高匿代理的情况
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // 处理多层代理的情况
        if (strpos($ip, ',') !== false) {
            // 输出第一个IP
            $ip = reset(explode(',', $ip));
        }
        return $ip;
    }
    /*获取客户端城市*/
 
    public function getCity($ip = ''){
        if($ip == ''){
            $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json";
            $ip=json_decode(file_get_contents($url),true);
            $data = $ip;
            }else{
            $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
            $ip=json_decode(file_get_contents($url));   
            if((string)$ip->code=='1'){
               return false;
            }
            $data = (array)$ip->data;
        }
        return $data;  
    }
    /**
     * 手机验证码登录
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     */
    public function register()
    {
        // $username = input('username');//真实姓名
        // if(empty($username )){
        //      $this->error('真实姓名不能为空');
        // }
        $password = input('password');//密码
        if(empty($password)){
             $this->error('密码不能为空');
        }
        $re_password = input('re_password');//确认密码
        if(empty($re_password)){
             $this->error('确认密码不能为空');
        }
        $mobile = input('mobile');//手机号
        if(empty($mobile)){
             $this->error('手机号不能为空');
        }
        $openid = input('openid');
        if($openid){
            $avatar = input('avatar');//头像
        }else{
            $avatar = '';//头像
        }
        //
        $parent_id = input('parent_id')?input('parent_id'):'';
        $type = input('type');//类型
        if(empty($type)){
             $this->error('身份类型不能为空');
        }
        if ( !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        //判断密码是否一致
        if($password!=$re_password){
            $this->error(__('密码不一致'));
        }
        //die;
        $ret = $this->auth->register($password,$type,$mobile,$openid,$avatar, [],$parent_id);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 完善会员个人信息
     *
     */
    public function profile()
    {
        //用户id
        $user = $this->auth->getUserinfo();
        $user_id=$user['id'];
        $state=input('state');
        if(empty($state)){
            $this->error('状态值不能为空');
        }
        $username = input('username');//姓名
        if(empty($username)){
            $this->error('真实姓名不能为空');
        }
       // $phone = input('phone');//手机号
        $work = input('work');//工种
        if(empty($work)){
            $this->error('工种不能为空');
        }
        $level = input('level');//级别
        if(empty($level)){
            $this->error('级别不能为空');
        }

        $province = input('province');//省份
        if(empty($province)){
            $this->error('省份不能为空');
        }
        $city = input('city');//城市
        if(empty($city)){
            $this->error('城市不能为空');
        }
        // $avatar = input('avatar', '', 'trim,strip_tags,htmlspecialchars');
        // if(empty($avatar)){
        //     $this->error('头像不能为空');
        // }
        $where['username']=$username;
        $where['id']=$user_id;
        $new = db('User')->field('id,username')->where($where)->find();
        if ($new) {
            $data['username']=$username;
            //$data['phone']=$phone;
            $data['work']=$work;
            $data['level']=$level;
            $data['province']=$province;
            $data['city']=$city;
            $data['address']=$province.$city;
            //$data['avatar']=$avatar;
            $data['state']=$state;
            //dump($data);
            //die;
            $r=db('User')->where(['id'=>$user_id])->update($data);
        }
        
        $this->success('修改成功');
       
       
    }

    /**
     * 更换手机号
     */
    public function replace(){
        //用户id
        $user = $this->auth->getUserinfo();
        $user_id=$user['id'];
        $mobile = input("mobile");
        $captcha = input("captcha");
        //查找数据库手机号是否存在
        $newmobile=db('User')->where(['mobile'=>$mobile])->find();
        if($newmobile){
            $this->error('手机号已存在');
        }
        //验证
        $A_Sms= new \SmsApi();
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }

        $verifyPhone = $A_Sms ->checkAppCode($mobile, $captcha);
        if (!$verifyPhone) {
            $this->error(__('Captcha is incorrect'));
        }
        $data['mobile']=$mobile;
        $r=db('user')->where(['id'=>$user_id])->update($data);
        if($r){
            $this->success('更换手机号成功');
        }else{
            $this->error('操作失败');
        }
    }

    /**
     * 忘记密码
     *
     */
    public function resetpwd()
    {
        $mobile = input("mobile");
        $newpassword = input("newpassword");//新密码
        $captcha = input("captcha");
        $repassword = input("repassword");//确认密码
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证
        $A_Sms= new \SmsApi();
        //查找数据库手机号是否存在
        $newmobile=db('User')->where(['mobile'=>$mobile])->find();
        if(empty($newmobile)){
            $this->error('用户名不存在');
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if (!$user) {
            $this->error(__('User not found'));
        }

        $verifyPhone = $A_Sms ->checkAppCode($mobile, $captcha);
        if (!$verifyPhone) {
            $this->error(__('Captcha is incorrect'));
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
     /**
     * 获取手机号验证码
     *
     * @param string $email   手机号
     * @param string $captcha 验证码
     */
    public function code($mobile){
        //  发送短信
        $A_Sms= new \SmsApi();
        $res = $A_Sms ->send($mobile);
        if($res){
            $this->success('验证码发送成功');
        }else{
            $this->error('验证码发送失败');
        }
    }
     
     /**
     * 个人信息
     *
     */
    public function information(){
        //用户id
        $user = $this->auth->getUserinfo();
        $user_id=$user['id'];
        $list=db('User')->field('id,username,mobile,avatar,work,level,province,city,type,phone,growth,state')->where(['id'=>$user_id])->find();
        $where['low']=array('<=',$list['growth']);
        $where['high']=array('>=',$list['growth']);
        //等级 成长值
        $scope=db('scope')->where($where)->find();
        //dump($scope);
        if($scope){
            //等级名
            $list['scopename']=$scope['scope'];
            $list['highscope']=$scope['high'];
            //下个等级
            if($scope['id']==3){
                $list['nextscope']=$scope['high']-$list['growth']; 
            }else{
                $id=$scope['id']+1;
                $next=db('scope')->where(['id'=>$id])->find();
                $list['nextscope']=$next['low']-$list['growth'];
                $list['nextname']=$next['scope'];
            }
            //等级范围
            $list['fan']=round($list['growth']/$scope['high'],2)*100;
        }
        //dump($scope);
        $this->success('查询成功',$list);
    }

    /**
     * 我的收藏
     */
    public function collectInfo(){
        //用户id
        $user = $this->auth->getUserinfo();
        $user_id=$user['id'];
        $limit=input('limit')?input('limit'):10;
        $page=input('page')?input('page'):1;
        $arr=db('User')->field('id,username,avatar,type')->where(['id'=>$user_id])->find();
       // dump($arr);
        //die;
        //1是工人显示收藏工作 
        $where['user_id']=$user_id;
        if($arr['type']==1){
            $where['type']=2;
            $list= db('Collection')->where($where)->order('addtime desc')->page($page,$limit)->select();
            foreach($list as $k=>$v){
                $work = db('Work')->field('id,title,address,work_time,user_id,createtime')->where(['id'=>$v['work_id']])->find();
                if($work){
                    //发布招工用户信息
                    $boss=db('User')->field('id,username,avatar,mobile')->where(['id'=>$work['user_id']])->find();
                    $list[$k]['username']=$boss['username'];
                    $list[$k]['avatar']=$boss['avatar'];
                    $list[$k]['mobile']=$boss['mobile'];
                    $list[$k]['title']=$work['title'];
                    $list[$k]['address']=$work['address'];
                    $list[$k]['work_time']=$work['work_time'];
                    $list[$k]['createtime']=date('Y-m-d',$work['createtime']);
                }
            }
        }
        //2是工头显示收藏工人
        if($arr['type']==2){
            $where['type']=1;
            $list= db('Collection')->where($where)->order('addtime desc')->page($page,$limit)->select();
            foreach($list as $k=>$v){
                $newuser = db('User')->field('id,mobile,username,avatar,work,level,address')->where(['id'=>$v['byuser_id']])->find();
                $list[$k]['mobile']=$newuser['mobile'];
                $list[$k]['username']=$newuser['username'];
                $list[$k]['avatar']=$newuser['avatar'];
               // $list[$k]['work']=$newuser['work'];
                if($newuser['work']==1){
                    $list[$k]['work']='结构';
                }
                if($newuser['work']==2){
                    $list[$k]['work']='管道';
                }
                if($newuser['work']==3){
                    $list[$k]['work']='纯水';
                }
                if($newuser['work']==4){
                    $list[$k]['work']='电工';
                }
                //级别:1=小工,2=中工,3=大工,4=带班
                if($newuser['level']==1){
                    $list[$k]['level']='小工';
                }
                if($newuser['level']==2){
                    $list[$k]['level']='中工';
                }
                if($newuser['level']==3){
                    $list[$k]['level']='大工';
                }
                if($newuser['level']==4){
                    $list[$k]['level']='带班';
                }
               // $list[$k]['level']=$newuser['level'];
            }
        }
        $this->success('查询成功',$list);
        //var_dump($list);
    }

    /**
     * 我的评论
    */
    public function myComment(){
        //用户id
        $user = $this->auth->getUserinfo();
        $user_id=$user['id'];
        $limit=input('limit')?input('limit'):10;
        $page=input('page')?input('page'):1;
        $list=db('Comments')->where(['user_id'=>$user_id])->order('addtime desc')->page($page,$limit)->select();
        foreach($list as $k=>$v){
            $boss=db('User')->where(['id'=>$v['fromuser_id']])->find();
            $list[$k]['username']=$boss['username'];
            $list[$k]['avatar']=$boss['avatar'];
            $list[$k]['mobile']=$boss['mobile'];
            $list[$k]['addtime']=date('Y-m-d',$v['addtime']);
        }
        $this->success('查询成功',$list);
    }

    /**
     * 会员
    */
   public function vipInfo(){
    //用户id
    $user = $this->auth->getUserinfo();
    $user_id=$user['id'];
    $list=db('Vipprice')->select();
    $this->success('查询成功',$list);
   }

    /**
     * 广告列表
    */
    public function adv(){
        $list=db('Adv')->select();
        $this->success('查询成功',$list);
    }


   
}
